chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'savePassword') {
    const { password, timestamp } = request.data;
    chrome.storage.local.get('passwordHistory', function(data) {
      const history = data.passwordHistory || [];
      history.push({ password, timestamp });
      // 按时间降序排序
      history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
      // 限制历史记录数量为10条
      if (history.length > 10) {
        history.splice(10); // 删除多余的记录
      }
      chrome.storage.local.set({ passwordHistory: history });
    });
  } else if (request.action === 'getPasswordHistory') {
    chrome.storage.local.get('passwordHistory', function(data) {
      const history = data.passwordHistory || [];
      // 将时间转换为北京时间
      const formattedHistory = history.map(entry => ({
        ...entry,
        timestamp: new Date(entry.timestamp).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
      }));
      sendResponse({ history: formattedHistory });
    });
    return true; // 保持消息通道打开，直到 sendResponse 被调用
  }
});